package com.maven.plugins.mybatis.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.maven.plugins.mybatis.core.Column;
import com.maven.plugins.mybatis.core.Context;

/**
 * 数据库连接工具
 * 
 * @author : fredia
 * @email : trumpey@163.com
 * @since : 2017年11月23日
 * @version : v0.0.1
 */
@SuppressWarnings(value = "unchecked")
public class DbUtils {
	public static List<Column> getColumns(Context ctx, String tableName) {
		Connection conn = null;
		Statement stmt = null;
		@SuppressWarnings("rawtypes")
		List result = new ArrayList();
		try {
			Properties properties = ctx.getJdbcProperties();

			Class.forName(properties.getProperty("driverClass", "com.mysql.jdbc.Driver"));

			conn = DriverManager.getConnection(properties.getProperty("connectionURL"), properties.getProperty("uName"),
					properties.getProperty("password"));

			stmt = conn.createStatement();
			StringBuilder sql = new StringBuilder(
					"select  column_name, column_comment, column_type from information_schema.columns where ");

			sql.append("table_schema ='" + ctx.getSchema() + "' and ").append("table_name = '" + tableName + "'");

			ResultSet rs = stmt.executeQuery(sql.toString());
			while (rs.next()) {
				String type = rs.getString("column_type");
				if (type.indexOf("(") != -1) {
					type = type.substring(0, type.indexOf("("));
				}
				result.add(new Column(rs.getString("column_name"), type, rs.getString("column_comment")));
			}

			rs.close();
		} catch (SQLException se) {
			se.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (stmt != null)
					stmt.close();
			} catch (SQLException se2) {
			}
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException se) {
				se.printStackTrace();
			}
		}
		return result;
	}
}